package com.ts.graphql.client;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.StringJoiner;

/**
 * GraphQL 请求
 * @author suyi
 */
public class GraphQlRequest {

    private GraphQlRequestType type;
    private Collection<GraphQlOperation> units;

    public GraphQlRequest(GraphQlRequestType type, Collection<GraphQlOperation> units) {
        this.type = type;
        this.units = units;
    }

    private static final int DEFAULT_UNIT_NUM = 10;
    public GraphQlRequest(GraphQlRequestType type) {
        this.type = type;
        this.units = new ArrayList<>(DEFAULT_UNIT_NUM);
    }

    public boolean addGraphQlRequestUnit(GraphQlOperation graphQlRequestUnit) {
        return units.add(graphQlRequestUnit);
    }

    public boolean removeGraphQlRequestUnit(GraphQlOperation graphQlRequestUnit) {
        return units.remove(graphQlRequestUnit);
    }

    /**
     * GraphQL 请求单元
     * ${请求类型} {
     *     ${请求单元} ...
     * }
     */
    final static String GRAPH_REQUEST_TEMPLATE = "%s { %s }";
    @Override
    public String toString() {
        return String.format(GRAPH_REQUEST_TEMPLATE, type.value, handleUnits());
    }

    public String toString(boolean encode) {
        String s =  toString();
        if (encode) {
            try {
                s = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
            } catch (UnsupportedEncodingException ignored) {
            }
        }
        return s;
    }

    private String handleUnits() {
        StringJoiner stringJoiner = new StringJoiner(" ");
        for (GraphQlOperation unit : units) {
            stringJoiner.add(unit.toString());
        }
        return stringJoiner.toString();
    }

}